// pages/choiceCommunity/choiceCommunity.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    villageList: [], //园区列表
    searchName: '', //搜索园区名
    village: {},
    location: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading();
    this.getVillage();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getLocation();
  },


  /**
   * 获取园区列表
   */
  getVillage() {
    var that = this;
    app.ajax({
      url: 'Salesman/Card/getPartnerVillage',
      data: {
        village_name: that.data.searchName,
        // lat: that.data.location.lat,
        // lng: that.data.location.lng,
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.code == 1000) {
          that.setData({
            villageList: res.data.data
          });
          that.originList = JSON.parse(JSON.stringify(res.data.data))
        }
      }
    })
  },
  //获取当前位置
  getLocation() {
    var that = this;
    wx.getLocation({
      success: function (res) {
        //console.log(res)
        let location = {}
        location.lat = res.latitude;
        location.lng = res.longitude;
        that.setData({
          location: location
        })
        that.getVillage();
      },
      fail: function () {
        app.showModal("", "需要地理位置定位,请先授权", function () {
          // console.log('进来的1');
          wx.openSetting({
            success(res) {
              // console.log('进来的2');
              if (res.authSetting['scope.userLocation'] == true) {
                // console.log('进来的3');
                // that.position();
              }
            },
            fail(res) {

            }
          })
        }, function () {
          app.showToast('很抱歉,无法获取您的位置,请返回重试!');
        });
      }
    })
  },
  //搜索园区
  searchName(e) {
    const originList = this.originList;
    const val = e.detail.value;
    if (originList.length <= 0) {
      return false;
    }
    let list = originList.filter(current => {
      let str = [current.province_name, current.city_name, current.area_name, current.address].join("");
      return current.village_name.includes(val) || str.includes(val)
    })
    this.setData({
      villageList: list,
      searchName: val
    })

  },
  //选择园区
  chooseVillage(e) {
    const village = e.currentTarget.dataset.village;
    this.setData({
      village
    })
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromOpenedPage', {
      ...village
    });
    wx.navigateBack({
      delta: 1
    })
  }
})